package com.controller.base;

import com.common.FastDFSUtil;
import com.common.JSONUtil;
import com.common.ResultUtil;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping(value = "/fileUpload")
public class FileUploadController extends BaseLocalController {

    //    @Value("${FILE.SYSTEM.SERVER}")
    private String FILE_SYSTEM_SERVER = "/ueditor/jsp/upload/image/";

    @ResponseBody
    @RequestMapping(value = "/ueditorUpload.htm", method = RequestMethod.POST)
    public String ueditorUpload(@RequestParam("upfile") MultipartFile file,HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap<>();
        try {
            File targetFile=null;
            String msg="";//返回存储路径
            int code=1;
            String fileName=file.getOriginalFilename();//获取文件名加后缀
            if(fileName!=null&&fileName!=""){
                String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/ueditor/jsp/upload/image/";//存储路径
                String path = request.getSession().getServletContext().getRealPath("ueditor/jsp/upload/image"); //文件存储位置
                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名

                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                //先判断文件是否存在
                String fileAdd = formatter.format(new Date());
                File file1 =new File(path+"/"+fileAdd);
                //如果文件夹不存在则创建
                if(!file1 .exists()  && !file1 .isDirectory()){
                    file1 .mkdir();
                }
                targetFile = new File(file1, fileName);
                try {
                    file.transferTo(targetFile);
                    msg=returnUrl+fileAdd+"/"+fileName;
                    code=0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            map.put("state", "SUCCESS");
            map.put("size", file.getSize());
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", "文件上传失败");
            map.put("url", "");
            map.put("size", "");
        }
        return JSONUtil.object2String(map);
    }

    @ResponseBody
    @RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
    public ResultUtil upload(MultipartFile file,HttpServletRequest request) throws IOException {
        ResultUtil resultUtil = ResultUtil.newInstance();
        try {
            File targetFile=null;
            String msg="";//返回存储路径
            int code=1;
            String fileName=file.getOriginalFilename();//获取文件名加后缀
            if(fileName!=null&&fileName!=""){
                String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/ueditor/jsp/upload/image/";//存储路径
                String path = request.getSession().getServletContext().getRealPath("ueditor/jsp/upload/image"); //文件存储位置
                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名

                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                //先判断文件是否存在
                String fileAdd = formatter.format(new Date());
                File file1 =new File(path+"/"+fileAdd);
                //如果文件夹不存在则创建
                if(!file1 .exists()  && !file1 .isDirectory()){
                    file1 .mkdir();
                }
                targetFile = new File(file1, fileName);
                try {
                    file.transferTo(targetFile);
                    msg=returnUrl+fileAdd+"/"+fileName;
                    code=0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultUtil.setStatus(ResultUtil.FAILED);
            resultUtil.setMessage("上传失败" + e.getMessage());
        }
        return resultUtil;
    }

    @ResponseBody
    @RequestMapping(value = "/delete.htm")
    public ResultUtil delete(String file) throws IOException {
        ResultUtil resultUtil = ResultUtil.newInstance();
        FastDFSUtil fastDFSUtil = new FastDFSUtil("classpath:fdfs_client.conf");
        String fileId = StringUtils.replace(file, FILE_SYSTEM_SERVER + "/", "");
        try {
//            fastDFSUtil.deleteFile(fileId);
            resultUtil.setMessage("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            resultUtil.setStatus(ResultUtil.FAILED);
        }
        return resultUtil;
    }
    /***
     * 保存文件
     * @param file
     * @return
     */
    private boolean saveFile(MultipartFile file, String path) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                File filepath = new File(path);
                //如果文件夹不存在则创建
                if (!filepath.exists() && filepath.isDirectory())
                    filepath.mkdirs();
                // 文件保存路径
                String savePath = path + file.getOriginalFilename();
                // 转存文件
                file.transferTo(new File(savePath));
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}